<script>
export default {
  name: "Role.vue",
  data() {
    return {
      tableData: [],
      name: "",
      currentPage: 1,
      pageSize: 5,
      total: 0,
      loading: true,
      multipleSelection: [],
      dialogFormVisible: false,
      form: {},
      formLabelWidth: '150px',
      dialogTreeVisible: false,
      dialogFormVisible1: false,
      menuData: [],
      expands: [],
      checks: [],
      props: {
        label: 'menuName',
        children: "submenuList"
      },
      ids: [],
      checkStrictly: false,
      roleFlag:null,
      roleId: 0
    }
  },
  created() {
    this.load();
  },
  methods: {
    load() {
      this.request.get("/role/selectAll", {
        params: {
          name: this.name,
          currentPage: this.currentPage,
          pageSize: this.pageSize,
        }
      }).then(res => {
        this.tableData = res.data.records;
        this.loading = false;
        this.total = res.data.total;

      });
      this.request.get("/menu/ids").then(res => {
        this.ids = res.data;
      })
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.load();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.load();
    },
    reset() {
      this.name = "";
      this.currentPage = 1;
      this.pageSize = 5;
      this.total = 0;
      this.load();
    },
    handleDelete(id) {
      this.request.delete("/role/delete/" + id).then(res => {
        if (res.code == 200) {
          this.$message({
            message: '删除成功',
            type: 'success',
            center: true
          });
          this.load();
        } else {
          this.$message({
            showClose: true,
            message:  res.msg,
            type: 'error'
          });
        }
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map((a) => a.roleId);
      console.log(this.multipleSelection);
    },
    handleBatchRemove() {
      let ids = this.multipleSelection;
      this.request.post("/role/deleteBatch", ids).then(res => {
        if (res.code == 200) {
          this.$message({
            message: '删除成功',
            type: 'success',
            center: true
          });
          this.load();
        } else {
          this.$message({
            center: true,
            message:  res.msg,
            type: 'error'
          });
        }
      })
    },
    handleEdit(row) {
      this.form = row;
      this.roleId = row.roleId;
      this.dialogFormVisible1 = true;
    },
    edit() {
    this.request.post("/role/edit/"+this.roleId,this.form).then(res=>{
      if (res.code === 200) {
        this.$message({
          message: '角色修改成功',
          type: 'success',
          center: true
        });
        this.dialogFormVisible1 = false;
        this.form = {};
        this.load();
      } else {
        this.$message({
          message: res.msg,
          type: 'error',
          center: true
        });
      }
    })
    },
    handleSave(){
      this.form={};
      this.dialogFormVisible=true;
    },
    save() {
      this.request.post("/role/save", this.form).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '角色创建成功',
            type: 'success',
            center: true
          });
          this.dialogFormVisible = false;
          this.form = {
            roleName: null,
            description: null,
            flag: null,
            status: 1
          };
          this.load();
        } else {
          this.$message({
            message:  res.msg,
            type: 'error',
            center: true
          });
        }
      })
    },
   selectMenu(role) {
     this.checkStrictly = true;
      this.roleId = role.roleId;
      this.roleFlag=role.flag;
      this.request.get("/menu/selectAll").then(res => {
        this.menuData = res.data;
        this.expands = this.menuData.map(m => m.menuId);
      });

        this.request.get("/role-menu/save/" + this.roleId).then(res => {
        // this.ids.forEach(id => {
        //   if (!this.checks.includes(id)) {
        //     // 可能会报错：Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'setChecked')
        //     this.$nextTick(() => {
        //       this.$refs.tree.setChecked(id, true,false)
        //     })
            this.$nextTick(() => {
              const checks=res.data;
              this.$refs.tree.setCheckedKeys(checks);
              this.checkStrictly = false
            })
      })
     this.dialogTreeVisible = true;
    },
    saveRoleMenu() {
      this.request.post("/role-menu/save/" + this.roleId, this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '菜单分配成功',
            type: 'success',
            center: true
          });
          this.dialogTreeVisible = false;
          if(this.roleFlag=='ROLE_ADMIN'){
            this.$store.commit("logout");
          }
        } else {
          this.$message({
            message:  res.msg,
            type: 'error',
            center: true
          });
          this.load();
        }
      });
    },
    changeEnable(role) {
    this.request.get("/role/edit/"+role.roleId,{
     params:{
      status:role.status
     }}).then(res=>{
      if(res.code===200){
        if(role.flag==='ROLE_ADMIN'){
          this.$store.commit("logout");
        }else{
        this.$message({
          message: '角色状态修改成功',
          type: 'success',
          center: true
        });
        }
      }else{
        this.$message({
          message:  res.msg,
          type: 'error',
          center: true
        });
      }
    })
    },
    headerBg({row,rowIndex}){
      if(rowIndex==0){
        return 'headerBgClass';
      }
    }
  }
}
</script>

<template>
  <div>
    <div>
      <el-input style="width:160px" v-model="name" suffix-icon="el-icon-search" placeholder="请输入角色名称"></el-input>
      <el-button type="primary" style="margin-left: 5px" @click="load">搜索</el-button>
      <el-button type="warning" style="margin-left: 5px" @click="reset">重置</el-button>
    </div>
    <div style="margin:10px 0px">
      <el-button type="primary" class="ml-5" icon="el-icon-circle-plus-outline" @click="handleSave">新增
      </el-button>
      <el-dialog title="新增角色" :visible.sync="dialogFormVisible" width="25%" center>
        <el-form :model="form">
          <el-form-item label="角色名称" :label-width="formLabelWidth">
            <el-input v-model="form.roleName" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="角色描述" :label-width="formLabelWidth">
            <el-input v-model="form.description" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="角色唯一标识" :label-width="formLabelWidth">
            <el-input v-model="form.flag" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="角色状态" :label-width="formLabelWidth">
            <el-radio v-model="form.status" label="false">停用</el-radio>
            <el-radio v-model="form.status" label="true">可用</el-radio>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="save">确 定</el-button>
          <el-button @click="dialogFormVisible = false">取 消</el-button>
        </div>
      </el-dialog>
      <el-popconfirm
          confirm-button-text='确定'
          cancel-button-text='我再想想'
          icon="el-icon-info"
          icon-color="red"
          title="你确定批量删除吗？"
          @confirm="handleBatchRemove"
          class="ml-5"
      >
        <el-button type="danger" class="ml-5" icon="el-icon-remove-outline" slot="reference">批量删除</el-button>
      </el-popconfirm>
    </div>
    <el-table :data="tableData"
              border stripe
              v-loading="loading"
              max-height="550"
              :header-cell-class-name="headerBg"
              element-loading-text="拼命加载中"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(255,225,255, 0.1)"
              @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55px" align="center"></el-table-column>
      <el-table-column prop="roleId" label="ID" width="55px" align="center">
      </el-table-column>
      <el-table-column prop="roleName" label="角色名称" width="100px" align="center">
      </el-table-column>
      <el-table-column prop="description" label="角色描述" align="center">
      </el-table-column>
      <el-table-column label="角色状态" align="center">
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ccc"
              @change="changeEnable(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="info" icon="el-icon-s-grid" class="mr-5" @click="selectMenu(scope.row)">分配菜单</el-button>
          <el-dialog title="分配菜单" :visible.sync="dialogTreeVisible" width="25%">
            <el-tree
                :props="props"
                :data="menuData"
                show-checkbox
                ref="tree"
                :check-strictly="checkStrictly"
                :default-expand-all="true"
                node-key="menuId"
                :default-expanded-keys="expands">
               <span class="custom-tree-node" slot-scope="{node,data}">
                <span><i :class="data.icon"></i>{{ data.menuName }}</span>
               </span>
            </el-tree>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogTreeVisible = false">取 消</el-button>
              <el-button type="primary" @click="saveRoleMenu">确 定</el-button>
            </div>
          </el-dialog>
          <el-button type="success" icon="el-icon-edit" style="margin-left: 5px" @click="handleEdit(scope.row)">编辑</el-button>
          <el-dialog title="编辑角色" :visible.sync="dialogFormVisible1" width="25%" center>
            <el-form :model="form">
              <el-form-item label="角色名称" :label-width="formLabelWidth">
                <el-input v-model="form.roleName" autocomplete="off" clearable></el-input>
              </el-form-item>
              <el-form-item label="角色描述" :label-width="formLabelWidth">
                <el-input v-model="form.description" autocomplete="off" clearable></el-input>
              </el-form-item>
              <el-form-item label="角色唯一标识" :label-width="formLabelWidth">
                <el-input v-model="form.flag" autocomplete="off" clearable></el-input>
              </el-form-item>
              <el-form-item label="角色状态" :label-width="formLabelWidth">
                <el-radio v-model="form.status" :label="false">停用</el-radio>
                <el-radio v-model="form.status" :label="true">可用</el-radio>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="edit">确 定</el-button>
              <el-button @click="dialogFormVisible1 = false">取 消</el-button>
            </div>
          </el-dialog>
          <el-popconfirm
              class="ml-5"
              confirm-button-text='确定'
              cancel-button-text='我再想想'
              icon="el-icon-info"
              icon-color="red"
              title="您确定删除吗？"
              @confirm="handleDelete(scope.row.roleId)"
          >
            <el-button type="danger" icon="el-icon-delete" slot="reference">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding:10px 0px">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<style scoped>
.headerBgClass{
  background-color: #cccccc !important;
}
</style>
